import axios from 'axios'
import {Toast} from 'vant'
import i18n from "@/locale/index";
import {encrypt, decrypt} from '@/utils/encipher'
import router from "@/router";

const {t} = i18n.global
const isProd = process.env.NODE_ENV === 'production'
const isTest = process.env.NODE_ENV === 'serveTest'
const prodUrl = window.origin + '/app-domain/api/'
const baseUrl = isProd ? prodUrl : isTest ? prodUrl : '/serveApi/api'
// 创建axios实例
const service = axios.create({
    timeout: 1000 * 60, // 请求超时时间ss
    baseURL: baseUrl
})
const codeMessage = {
    404: 'server_unconnect',
    1000: 'connect_time_out',
    502: t('server Error')
};
// request拦截器
service.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    const userId = localStorage.getItem('userId')
    const locale = localStorage.getItem('locale')
    if (token) {
        config.headers.token = token
    }
    if (userId) {
        config.headers.userId = userId
    }
    config.headers.language = locale || 'en_ph'
    //
    if (isProd) {
        if (config.method === 'post' && config.data) {
            // 对象加密
            if (config.data && Object.prototype.toString.call(config.data) === '[object Object]') {
                config.data = {
                    key: encrypt(JSON.stringify(config.data)),
                }
            }
            // 数组加密
            if (config.data && Object.prototype.toString.call(config.data) === '[object Array]') {
                config.data = {
                    key: encrypt(JSON.stringify(config.data))
                }
            }

        }
    }

    return config
}, error => {
    Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
    response => {
        // 解密相应参数
        let DE_DATA
        if (isProd) {
            if (response.data.key) {
                DE_DATA = JSON.parse(decrypt(response.data.key))
            }
        }
        const {code, message} = DE_DATA || response.data
        const codeSuccess = [1, 10,6020]
        if (codeSuccess.indexOf(code) === -1) {
            Toast({
                message: message
            })
            /**
             * code 100用户登录过期
             */
            if (code === 100) {
                const indexArr = ['phone', 'userId', 'loanInfo', 'token', 'userWriteInfo', 'userInfoVerify', 'orderId', 'homeProductList', 'loanInfo', 'productInfo']
                indexArr.forEach(item => {
                    localStorage.removeItem(item)
                })
                router.replace('/JFLAWJLfjkw')
            }
        }
        return isProd ? (DE_DATA || response.data) : response.data
    },
    error => {
        let code
        try {
            code = error.response.status
        } catch {
            //请求超时
            if (error.code === 'ECONNABORTED') {
                code = 1000
            }
        }
        Toast({
            message: codeMessage[code] ? code + " " + codeMessage[code] : error,
        })
        return Promise.reject()
    }
)

export default service
